#include "mainwindow.h"
#include "ui_mainwindow.h"

static const QLatin1String myServiceUuid("{0000ffe0-0000-1000-8000-00805f9b34fb}");

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    gCurCol = 0;
    gCurRow = 0;

    discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
    connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,this, &MainWindow::deviceDiscovered);

    QStringList recList = {"DeviceName", "Mac", "Rssi"};

    //设置列
    ui->tableWidget->setColumnCount(3);
    ui->tableWidget->setHorizontalHeaderLabels(recList);

    ui->tableWidget->setColumnWidth(0, 300);
    ui->tableWidget->setColumnWidth(1, 200);
    ui->tableWidget->setColumnWidth(2, 50);

    ui->tableWidget->setAlternatingRowColors(true);

    //QSS表：
    ui->tableWidget->setStyleSheet("QTableView{\
        background-color: rgb(232,241,250); \
        alternate-background-color: rgb(250, 250, 250); \
        font-size: 9pt; \
    }");

    QStringList uuidList = {"UUID"};

    //设置列
    ui->serviceTableWidget->setColumnCount(1);
    ui->serviceTableWidget->setHorizontalHeaderLabels(uuidList);

    ui->serviceTableWidget->setColumnWidth(0, 300);

    ui->serviceTableWidget->setAlternatingRowColors(true);

    //QSS表：
    ui->serviceTableWidget->setStyleSheet("QTableView{\
        background-color: rgb(232,241,250); \
        alternate-background-color: rgb(250, 250, 250); \
        font-size: 9pt; \
    }");

    ui->scanBar->setRange(0, 100); // 设置进度条的范围从0到100
    ui->scanBar->show(); // 显示进度条
    ui->scanBar->setValue(0);

    // 创建一个定时器
    gBarTimer = new QTimer(this);
    gBarVal = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::deviceDiscovered(const QBluetoothDeviceInfo &device)
{
    qDebug() << "发现新设备：" << device.name() << '(' << device.address().toString() << ')' << device.rssi();
    ui->tableWidget->insertRow(gCurRow);
    ui->tableWidget->setItem(gCurRow, 0, new QTableWidgetItem(device.name()));
    ui->tableWidget->setItem(gCurRow, 1, new QTableWidgetItem(device.address().toString()));
    ui->tableWidget->setItem(gCurRow, 2, new QTableWidgetItem(QString::number(device.rssi())));
    gCurCol++;
    gCurRow++;
}

void MainWindow::on_scanButton_clicked()
{
//    discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::ClassicMethod);
    ui->tableWidget->clear();
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    QStringList recList = {"DeviceName", "Mac", "Rssi"};
    //设置列
    ui->tableWidget->setColumnCount(3);
    ui->tableWidget->setHorizontalHeaderLabels(recList);

    ui->tableWidget->setColumnWidth(0, 300);
    ui->tableWidget->setColumnWidth(1, 200);
    ui->tableWidget->setColumnWidth(2, 50);

    gCurCol = 0;
    gCurRow = 0;

    discoveryAgent->start();

    QObject::connect(gBarTimer, &QTimer::timeout, [&]() {
        // 每次定时器超时，进度条的值增加一点
        gBarVal = (gBarVal + 10) % 101; // 确保值在0到100之间循环
        ui->scanBar->setValue(gBarVal);

        if (gBarVal == ui->scanBar->maximum()) {
            gBarTimer->stop();
            discoveryAgent->stop();
            gBarVal = 0;
        }
    });
    gBarTimer->start(500); // 500ms
}

void MainWindow::on_tableWidget_itemSelectionChanged()
{
    int curRow = ui->tableWidget->currentRow();

    qDebug()<< "select: " + ui->tableWidget->item(curRow, 1)->text();

    ui->selectMacEdit->setText(ui->tableWidget->item(curRow, 1)->text());
}

void MainWindow::serviceDiscovered(const QBluetoothUuid &serviceUuid) {
    qDebug() << "Service discovered:" << serviceUuid;

    static int row = 0, rol = 0;
    ui->serviceTableWidget->insertRow(row);
    ui->serviceTableWidget->setItem(row, rol, new QTableWidgetItem(serviceUuid.toString()));

    ui->log->append(serviceUuid.toString());

    if (serviceUuid == QBluetoothUuid(myServiceUuid)) {
        service = controller->createServiceObject(serviceUuid, this);
        connect(service, &QLowEnergyService::stateChanged, this, [this](QLowEnergyService::ServiceState state) {
            if (state == QLowEnergyService::ServiceDiscovered) {
                qDebug() << "Service discovered.";
                const QLowEnergyCharacteristic hrChar = service->characteristic(QBluetoothUuid::HeartRateMeasurement);
                if (!hrChar.isValid()) {
                    qDebug() << "Heart Rate Measurement characteristic not found.";
                    return;
                }
                service->readCharacteristic(hrChar);

                writeCharacteristics = service->characteristic(QBluetoothUuid::HeartRateControlPoint);
                if (writeCharacteristics.isValid()) {
                    writeCharacteristic();
                }

                QLowEnergyDescriptor notificationDesc = hrChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
                if (notificationDesc.isValid()) {
                    service->writeDescriptor(notificationDesc, QByteArray::fromHex("0100"));
                }

                connect(service, &QLowEnergyService::characteristicChanged, this, &MainWindow::characteristicChanged);
            }
        });
        connect(service, &QLowEnergyService::characteristicRead, this, &MainWindow::characteristicRead);
        service->discoverDetails();
    }
}

void MainWindow::writeCharacteristic() {
    QByteArray value;
    value.append(char(1)); // Example value to write
    service->writeCharacteristic(writeCharacteristics, value);
}

void MainWindow::serviceScanDone() {
    qDebug() << "Service scan done.";

    ui->log->append("Service scan done.");
}

void MainWindow::characteristicRead(const QLowEnergyCharacteristic &info, const QByteArray &value) {
    qDebug() << "Characteristic read:" << info.uuid() << value.toHex();

    ui->log->append("Characteristic read:" + info.uuid().toString() + value.toHex());
}

void MainWindow::characteristicChanged(const QLowEnergyCharacteristic &info, const QByteArray &value) {
    qDebug() << "Characteristic changed:" << info.uuid() << value.toHex();

    ui->log->append("Characteristic read:" + info.uuid().toString() + value.toHex());
}

void MainWindow::on_connectButton_clicked()
{
     discoveryAgent->stop();

     QTableWidgetItem *item = ui->tableWidget->currentItem();
         if (!item)
             return;

    QString text = item->text();
    QString address = ui->selectMacEdit->text();
    qDebug() << address;
    QBluetoothAddress btAddress(address);
    QBluetoothDeviceInfo deviceInfo(btAddress, text, QBluetoothDeviceInfo::LowEnergyCoreConfiguration);

    controller = QLowEnergyController::createCentral(deviceInfo, this);
    connect(controller, &QLowEnergyController::serviceDiscovered, this, &MainWindow::serviceDiscovered);
    connect(controller, &QLowEnergyController::discoveryFinished, this, &MainWindow::serviceScanDone);
    connect(controller, &QLowEnergyController::connected, this, [this]() {
        controller->discoverServices();
    });
    connect(controller, static_cast<void(QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error), \
            this, [this](QLowEnergyController::Error error) {
        qDebug() << "Error:" << error;
    });

    controller->connectToDevice();
}

void MainWindow::on_disconnButton_clicked()
{
    // 断开连接
    controller->disconnectFromDevice();
}
